package com.yuncheng.spcyApi.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.annotation.Resource;


import cn.hutool.core.bean.BeanUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.entity.YcSysUserDepart;
import com.yuncheng.entity.YcSysUserRole;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.constant.SysUserConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.spcyApi.vo.jcy.HcyTjjlVo;
import com.yuncheng.vo.HttpResult;

import com.yuncheng.annotation.AutoLog;

import com.yuncheng.common.base.controller.BaseController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-核查员推荐记录
 * @Author: yuncheng
 * @Date: 2023-04-12
 * @Version: V1.0
 */
/*@Api(tags = "审评查验-核查员推荐记录接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsHcytjjl")*/
public class SpcyRsHcytjjlController extends BaseController<SpcyRsHcytjjl, ISpcyRsHcytjjlService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsHcytjjlController.class);

    @Resource
    private ISpcyRsHcytjjlService spcyRsHcytjjlService;

    @Resource
    private ISpcyRsTjgzjlService spcyRsTjgzjlService;

    @Resource
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    private ISpcyLogService spcyLogService;

    /**
     * 分页列表查询
     *
     * @param spcyRsHcytjjl
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "核查员推荐记录-分页列表查询")
    @ApiOperation(value = "核查员推荐记录-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SpcyRsHcytjjl spcyRsHcytjjl,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsHcytjjl> page = new Page<>(pageNo, pageSize);

        LambdaQueryWrapper<SpcyRsHcytjjl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFyear()),SpcyRsHcytjjl::getFyear,spcyRsHcytjjl.getFyear());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFbusmc()),SpcyRsHcytjjl::getFbusmc,spcyRsHcytjjl.getFbusmc());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFgzdw()),SpcyRsHcytjjl::getFgzdw,spcyRsHcytjjl.getFgzdw());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFtjzg()),SpcyRsHcytjjl::getFtjzg,spcyRsHcytjjl.getFtjzg());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFsfrx()),SpcyRsHcytjjl::getFsfrx,spcyRsHcytjjl.getFsfrx());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsHcytjjl.getFrxczr()),SpcyRsHcytjjl::getFrxczr,spcyRsHcytjjl.getFrxczr());
        IPage<SpcyRsHcytjjl> pageList = spcyRsHcytjjlService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 核查员推荐记录-添加
     *
     * @param hcyTjjlVo
     * @return
     */
    @AutoLog(value = "核查员推荐记录-添加")
    @ApiOperation(value = "核查员推荐记录-添加")
    @PostMapping(value = "/addHcyTj")
    public HttpResult<?> addHcyTj(@RequestBody HcyTjjlVo hcyTjjlVo) {
        if (StringUtils.isBlank(hcyTjjlVo.getFbusmc())){
            return HttpResult.error("姓名不能为空");
        }
        SpcyRsHcytjjl spcyRsHcytjjl = new SpcyRsHcytjjl();
        BeanUtil.copyProperties(hcyTjjlVo,spcyRsHcytjjl);
        String hcytjid = GetUuIdUtils.ReplaceUuId();
        spcyRsHcytjjl.setId(hcytjid);
        spcyRsHcytjjl.setFyear(DateConversionUtils.DateToYear(new Date()));
        spcyRsHcytjjlService.save(spcyRsHcytjjl);

        String operContent = "新增信息：";
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsHcytjjl);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJL,operContent,hcytjid, LogConstant.LOGS_RS_HCYTJJL, SpcyConstant.LOGS_SYS_TYPE_XZ);


        if (CollectionUtils.isNotEmpty(hcyTjjlVo.getGzjlList())){
            for (SpcyRsTjgzjl tjgzjl : hcyTjjlVo.getGzjlList()){
                tjgzjl.setId(GetUuIdUtils.ReplaceUuId());
                tjgzjl.setFhcytjid(hcytjid);
                tjgzjl.setFbusmc(hcyTjjlVo.getFbusmc());
                spcyRsTjgzjlService.save(tjgzjl);

                String operContent1 = "新增信息：";
                // 将map里面的属性和值转String
                Map<String, Object> beanMap1 = ObjectToMapUtils.objectToMap(tjgzjl);
                operContent1 += LogUtils.MapToStringMethod(beanMap1);
                spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJLGZJL,operContent1,hcytjid, LogConstant.LOGS_RS_HCYTJJLGZJL, SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }

        return HttpResult.ok("添加成功");
    }

    @AutoLog(value = "添加工作简历")
    @ApiOperation(value = "添加工作简历")
    @PostMapping(value = "addHcyGzjl")
    public HttpResult<?> addHcyGzjl(@RequestBody SpcyRsTjgzjl spcyRsTjgzjl){
        if (StringUtils.isBlank(spcyRsTjgzjl.getFhcytjid())){
            return HttpResult.error("主要参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(spcyRsTjgzjl.getFbusmc())){
            return HttpResult.error("主要参数丢失，请联系管理员");
        }
        spcyRsTjgzjl.setId(GetUuIdUtils.ReplaceUuId());
        spcyRsTjgzjlService.save(spcyRsTjgzjl);

        String operContent = "新增信息：";
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsTjgzjl);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJLGZJL,operContent,spcyRsTjgzjl.getFhcytjid(), LogConstant.LOGS_RS_HCYTJJLGZJL, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    @AutoLog(value = "核查员推荐记录-编辑")
    @ApiOperation(value = "核查员推荐记录-编辑")
    @ApiImplicitParam(name = "id",value = "核查员推荐记录id",required = true)
    @PutMapping(value = "/editHcyTj")
    public HttpResult<?> editHcyTj(@RequestBody HashMap<String, String> buffer) {
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("核查员推荐记录id不能为空");
        }
        String hcytjid = buffer.get("id");
        SpcyRsHcytjjl oldHcyYjUpdate = spcyRsHcytjjlService.getById(hcytjid);

        if (oldHcyYjUpdate == null){
            return HttpResult.error("当前核查员推荐记录基本信息数据不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldHcyYjUpdate);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        try {
            BeanUtils.populate(oldHcyYjUpdate, buffer);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        spcyRsHcytjjlService.updateById(oldHcyYjUpdate);

        String operContent = "基本信息修改：";

        operContent += LogUtils.BeanModifyMsg(oldHcyYjUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJL,operContent,hcytjid,LogConstant.LOGS_RS_HCYTJJL,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    @AutoLog(value = "核查员工作简历-编辑")
    @ApiOperation(value = "核查员工作简历-编辑")
    @ApiImplicitParam(name = "id",value = "核查员推荐记录id",required = true)
    @PutMapping(value = "/editHcyGzjl")
    public HttpResult<?> editHcyGzjl(@RequestBody HashMap<String, String> buffer) {
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("核查员工作简历id不能为空");
        }
        String hcytjid = buffer.get("id");
        SpcyRsTjgzjl oldGzjlUpdate = spcyRsTjgzjlService.getById(hcytjid);

        if (oldGzjlUpdate == null){
            return HttpResult.error("当前核查员工作简历基本信息数据不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldGzjlUpdate);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        try {
            BeanUtils.populate(oldGzjlUpdate, buffer);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        spcyRsTjgzjlService.updateById(oldGzjlUpdate);

        String operContent = "基本信息修改：";

        operContent += LogUtils.BeanModifyMsg(oldGzjlUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJLGZJL,operContent,hcytjid,LogConstant.LOGS_RS_HCYTJJLGZJL,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    @AutoLog(value = "通过工作简历id删除")
    @ApiOperation(value = "通过工作简历id删除")
    @DeleteMapping(value = "/deleteGzjl")
    public HttpResult<?> deleteGzjl(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsTjgzjl gzjl = spcyRsTjgzjlService.getById(id);
        if (gzjl != null) {
            spcyRsTjgzjlService.removeById(id);

            String operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(gzjl);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJLGZJL, operContent, id, LogConstant.LOGS_RS_HCYTJJLGZJL, SpcyConstant.LOGS_SYS_TYPE_SC);
        }else {
            return HttpResult.error("当前工作简历不存在，请重试");
        }
        return HttpResult.ok("删除成功");
    }

    @AutoLog(value = "核查员推荐记录-批量删除")
    @ApiOperation(value = "核查员推荐记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsHcytjjl> spcyRsHcytjjls = spcyRsHcytjjlService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyRsHcytjjls)){
            return HttpResult.error("数据不存在，请重试");
        }

        String operContent = "";
        for (SpcyRsHcytjjl hcytjjl : spcyRsHcytjjls){
            String id = hcytjjl.getId();
            spcyRsHcytjjlService.removeById(id);
            spcyRsTjgzjlService.remove(new LambdaQueryWrapper<SpcyRsTjgzjl>().eq(SpcyRsTjgzjl::getFhcytjid,id));

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(hcytjjl);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCYTJJL,operContent,id,LogConstant.LOGS_RS_HCYTJJL,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "核查员推荐记录-通过id查询")
    @ApiOperation(value = "核查员推荐记录-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsHcytjjl spcyRsHcytjjl = spcyRsHcytjjlService.getById(id);
        List<SpcyRsTjgzjl> gzjlList = spcyRsTjgzjlService.list(new LambdaQueryWrapper<SpcyRsTjgzjl>()
                .eq(SpcyRsTjgzjl::getFhcytjid, id));
        HcyTjjlVo hcyTjjlVo = new HcyTjjlVo();
        BeanUtil.copyProperties(spcyRsHcytjjl,hcyTjjlVo);
        hcyTjjlVo.setGzjlList(gzjlList);
        return HttpResult.ok(hcyTjjlVo);
    }

//    @AutoLog(value = "推荐核查员入选")
//    @ApiOperation(value = "推荐核查员入选")
//    @GetMapping(value = "beSelectdHcy")
    public HttpResult<?> beSelectdHcy(String id,String frxly){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        SpcyRsHcytjjl hcyTjjl = spcyRsHcytjjlService.getById(id);

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(hcyTjjl);
        if (hcyTjjl == null){
            return HttpResult.error("当前推荐核查员不存在,请重试");
        }
        hcyTjjl.setFrxsj(new Date());
        hcyTjjl.setFsfrx(SpcyConstant.SFRX_YES);
        hcyTjjl.setFrxczr(currentUser.getName());
        hcyTjjl.setFrxly(frxly);
        spcyRsHcytjjlService.updateById(hcyTjjl);

        String logNr = "入选核查员：";
        logNr += LogUtils.BeanModifyMsg(hcyTjjl,oldMap);
        spcyLogService.addLogs("入选核查员",logNr,id,LogConstant.LOGS_RS_HCYTJJL,SpcyConstant.LOGS_SYS_TYPE_BC);

        String fywflcode = "";
        String flx = "";
        String fxllx = "";
        if (StringUtils.isNotBlank(hcyTjjl.getFtjzg())){
            String ftjzg = hcyTjjl.getFtjzg();
            if (ftjzg.equals(SpcyConstant.TJZG_YPGMPJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YPSC;
                fxllx = SpcyConstant.XLLX_YP;
                flx = SpcyConstant.HCY_LX_YPSC;

            }else if (ftjzg.equals(SpcyConstant.TJZG_YPGCPJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YPZC;
                fxllx = SpcyConstant.XLLX_YP;
                flx = "";

            }else if (ftjzg.equals(SpcyConstant.TJZG_YPZCXCJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YPZC;
                fxllx = SpcyConstant.XLLX_YP;
                flx = "";

            }else if (ftjzg.equals(SpcyConstant.TJZG_GSPYPLLSQYJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YPJY;
                fxllx = SpcyConstant.XLLX_YP;
                flx = SpcyConstant.HCY_LX_YPLT;

            }else if (ftjzg.equals(SpcyConstant.TJZG_GSPYPPFQYJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YPJY;
                fxllx = SpcyConstant.XLLX_YP;
                flx = SpcyConstant.HCY_LX_YPLT;

            }else if (ftjzg.equals(SpcyConstant.TJZG_YLQXJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_YLQX;
                fxllx = SpcyConstant.XLLX_YLQX;
                flx = "";

            }else if (ftjzg.equals(SpcyConstant.TJZG_HZPJCY)){
                fywflcode = SpcyConstant.YWFL_CODE_HZP;
                fxllx = SpcyConstant.XLLX_HZP;
                flx = "";

            }
        }

        String userId = "";
        String username = hcyTjjl.getFbusmc();
        // 查询账号
        List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                .eq(YcSysUser::getUsername, username));
        if (CollectionUtils.isNotEmpty(userList)){
            return HttpResult.error("账号【"+username+"】已存在");
        }else {
            YcSysUser sysUser = new YcSysUser();
            userId = GetUuIdUtils.ReplaceUuId();
            sysUser.setId(userId);
            sysUser.setPassword(SysUserConstant.PASSWORD);
            sysUser.setSalt(SysUserConstant.SALT);
            sysUser.setWorkNo(userId);
            sysUser.setIsRealUser(SysUserConstant.IS_REAL_USER);
            sysUser.setStatus(Integer.valueOf(SysUserConstant.STATUS));
            sysUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG));
            sysUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
            sysUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
            sysUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码

            sysUser.setUsername(hcyTjjl.getFbusmc());
            sysUser.setRealname(hcyTjjl.getFbusmc());
            sysUser.setSex(hcyTjjl.getFsex());
            sysUser.setFgzdw(hcyTjjl.getFgzdw());
            sysUser.setPhone(hcyTjjl.getFphone());
            sysUser.setEmail(hcyTjjl.getFemail());
            sysUser.setFdwdh(hcyTjjl.getFdwdh());
            sysUser.setFcz(hcyTjjl.getFcz());
            sysUser.setBirthday(hcyTjjl.getFcsny());
            sysUser.setFcsgz(hcyTjjl.getFcsgz());

            ycSysUserService.save(sysUser);

            // 新增日志
            String addSysUserOper = "推荐核查员入库：";
            Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(sysUser);
            addSysUserOper += LogUtils.MapToStringMethod(addUserMap);
            spcyLogService.addLogs("推荐核查员入库", addSysUserOper, userId, LogConstant.LOGS_SYS_USER, SpcyConstant.LOGS_SYS_TYPE_XZ);

            // 新增部门用户关系
            YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
            ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserDepart.setUserId(userId);
            ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
            ycSysUserDepart.setPositionId(""); // 职务编号
            ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
            ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);

            // 用户部门 日志
            String ycAddUserDepartOperCont = "推荐核查员入库：用户名[" + sysUser.getRealname() + "]; 部门[" + SpcyConstant.HCY_ORGNAME + "]; " +
                    "用户编号[" + userId + "]; 部门编号[" + SpcyConstant.HCY_ORGID + "];";
            spcyLogService.addLogs("推荐核查员入库", ycAddUserDepartOperCont, userId, LogConstant.LOGS_SYS_USER_DEPT, SpcyConstant.LOGS_SYS_TYPE_XZ);

            String roleId = "";
            roleId = SpcyConstant.getRoleIdByCode(fywflcode);

            // 对用户角色进行自动授权
            YcSysUserRole userRole = new YcSysUserRole();
            userRole.setId(GetUuIdUtils.ReplaceUuId());
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            ycSysUserMapper.addYcSysUserRole(userRole);

            // 加新增和授权的日志
            String ycAddUserRoleOperCont = "推荐核查员入库：用户名[" + sysUser.getRealname() + "]; 用户编号[" + userId + "]; " +
                    "角色编号[" + roleId + "];]";
            spcyLogService.addLogs("推荐核查员入库", ycAddUserRoleOperCont, userId, LogConstant.LOGS_SYS_USER_ROLE, SpcyConstant.LOGS_SYS_TYPE_XZ);
        }

        SpcyRsHcy hcy = new SpcyRsHcy();
        List<SpcyRsHcy> hcyList = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                .eq(SpcyRsHcy::getFuserid, userId)
                .eq(SpcyRsHcy::getFywflcode, fywflcode)
        );
        if (CollectionUtils.isNotEmpty(hcyList)){
            return HttpResult.error("业务分类【"+fywflcode+"】+核查员【"+username+"】已存在,入库失败");
        }else {
            hcy.setFywflcode(fywflcode);
            hcy.setFuserid(userId);
            hcy.setFusertype(SpcyConstant.HCY_USERTYPE_JCY);
            hcy.setFxllx(fxllx);
            hcy.setFlx(flx);
            hcy.setFssk(SpcyConstant.HCY_SSK_JXK);
            spcyRsHcyService.save(hcy);

            //增加日志记录
            String addHcyOper = "推荐核查员入库";
            Map<String, Object> addHcyMap = ObjectToMapUtils.objectToMap(hcy);
            addHcyOper += LogUtils.MapToStringMethod(addHcyMap);
            spcyLogService.addLogs("推荐核查员入库",addHcyOper,userId,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XZ);
        }

        return HttpResult.ok();
    }


}
